<?php
/**
 * A simple description for this script
 *
 * PHP Version 5.2.0 or Upper version
 *
 * @package    Paylog
 * @author     Hidehito NOZAWA aka Suin <http://suin.asia>
 * @copyright  2010 Hidehito NOZAWA
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU GPL v2
 *
 */

abstract class Paylog_Abstract_Form
{
	const TEXT         = 1;
	const OPTION       = 2;
	const MULTI_OPTION = 3;

	protected $fields = array();
	protected $errors = array();

	public function field($name, $type, $default = null, $required = false, $options = array(), $validators = array())
	{
		$this->fields[$name]['value']      = $default;
		$this->fields[$name]['type']       = $type;
		$this->fields[$name]['default']    = $default;
		$this->fields[$name]['required']   = $required;
		$this->fields[$name]['validators'] = $validators; // user callback validators

		if ( $type == self::OPTION )
		{
			$this->fields[$name]['options'] = $options;
			$this->fields[$name]['validators'][] = 'singleValue';
			$this->fields[$name]['validators'][] = 'valueInOption';
		}
		elseif ( $type == self::MULTI_OPTION )
		{
			$this->fields[$name]['options'] = $options;
			$this->fields[$name]['validators'][] = 'valueInOption';
		}
	}

	public function setVar($name, $value)
	{
		$this->fields[$name]['value'] = $value;
	}

	public function getVar($name)
	{
		return $this->fields[$name]['value'];
	}

	public function setVars($fields)
	{
		foreach ( $this->fields as $key => $v )
		{
			if ( isset($fields[$key]) )
			{
				$this->setVar($key, $fields[$key]);
			}
		}
	}

	public function getVars()
	{
		$fields = array();

		foreach ( $this->fields as $name => $var )
		{
			$fields[$name] = $var['value'];
		}

		return $fields;
	}

	public function validatation($name)
	{
		$validators = $this->fields[$name]['validators'];

		foreach ( $validators as $validator )
		{
			$myValidator = '_validate'.ucfirst($validator);

			if ( method_exists($this, $myValidator) )
			{
				$this->$validator($name);
			}
		}
	}

	public function validatations()
	{
		foreach ( $this->fields as $key => $v )
		{
			$this->validatation($key);
		}
	}

	public function getErrors()
	{
		return $this->errors;
	}

	public function isError()
	{
		return ( count($this->errors) > 0 );
	}

	public function getOptions($name)
	{
		return $this->fields[$name]['options'];
	}

	protected function _validateSingleValue($name)
	{
		$value = $this->getVar($name);

		if ( is_array($value) )
		{
			$this->error[] = "Two or more option was selected.";
		}
	}

	protected function _validateValueInOption($name)
	{
		$value   = $this->getVar($name);
		$options = $this->getOptions($name);

		$i = 0;
		$isHash = false;

		foreach( $array as $k => $dummy )
		{
			if ( $k !== $i++ ) $isHash = true;
		}

		if ( $isHash and !isset($options[$value]) )
		{
			$this->errors[] = "Option error.";
		}
		elseif ( !in_array($value, $options) )
		{
			$this->errors[] = "Option error.";
		}
	}
}

?>
